#include <iostream>
#include "pro.hpp"
#include <string>
#include <strings.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/stat.h>
// #include <fcntl.h>
#include <memory>

// void client_side(int client_socket, struct sockaddr_in server_addr) {
//     TimeInfo time_info;

//     // 获取客户端当前时间
//     time_info.client_time = time(NULL);

//     // 向服务器发送客户端时间
//     sendto(client_socket, &time_info, sizeof(TimeInfo), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));

//     // 接收服务器发送的时间
//     recvfrom(client_socket, &time_info, sizeof(TimeInfo), 0, NULL, NULL);

//     // 打印客户端和服务器之间的时间差
//     printf("Client time: %s\n", ctime(&time_info.client_time));
//     printf("Server time: %s\n", ctime(&time_info.server_time));
//     printf("Difference: %ld seconds\n", time_info.server_time - time_info.client_time);
// }

namespace Client
{
    using namespace std;

    class udpClient
    {
    public:
        udpClient(const string &serverip, const uint16_t &serverport) : _serverip(serverip), _serverport(serverport), _sockfd(-1)
        {}
        void initClient()
        {
            // 创建socket
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "socket error: " << errno << " : " << strerror(errno) << endl;
                exit(2);
            }
            cout << "socket success: " << " : " << _sockfd << endl;
        }
        void start()
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            server.sin_port = htons(_serverport);
            char inbuff[BUFFSIZE];
            
            // while(1)
            // {
                // client_side(_sockfd, server);
                // sleep(3);
                Request request("Hello from client!what time is it now?");
                std::string request_header = request.wrap();
                cout << "修改前的时间" << ctime(&request._time.client_time) << endl;
                socklen_t server_addr_len = sizeof(server);
                // cout << "封装后的数据: " << request_header << endl;
                sendto(_sockfd, request_header.c_str(), request_header.size(), 0, (struct sockaddr*)&server, server_addr_len);
                // sleep(10);
                ssize_t recv_len = recvfrom(_sockfd, inbuff, sizeof(inbuff) - 1, MSG_WAITALL, (struct sockaddr*)&server, &server_addr_len);
                if (recv_len < 0) {
                    std::cerr << "Error: Cannot receive data."<< std::endl;
                    return;
                }
                // cout << "inbuff : " << inbuff << endl;
                std::string response_header(inbuff);
                // cout << "response_header : " << response_header << endl;
                Response response;
                response.message = response.unwrap(response_header);
                // cout << "解析后的数据 : " << response.message << endl;
                cout << "Client received: "<< response.message<< endl;
                // cout << response._time.server_time << endl;
                ////保存到本地
                change_local_time(response);
                // sleep(3);
                ////
                ///修改系统时间
                change_linux_time(response);
                ///
                cout << "UTC-Time : "<< ctime(&response._time.server_time) << endl;
                sleep(3);

            // }
        }
        void change_local_time(Response& response)
        {
            FILE *file = fopen("time.txt", "w");
            if (file == NULL) {
                perror("无法打开或创建文件\n");
                return;
            }

            // 使用fprintf将字符串写入文件
            fprintf(file, "%ld->UTC-TIME:%s", response._time.server_time, ctime(&response._time.server_time));

            // 使用fclose关闭文件
            fclose(file);
            printf("已修改本地时间\n");
        }
        void change_linux_time(Response& response)
        {
            struct tm* local_time = localtime(&response._time.server_time);
            time_t new_time_t = mktime(local_time);

            // 修改虚拟机的系统时间
            int result = stime(&new_time_t);
            if (result != 0) 
            {
                perror("权限不足，修改时间失败");
                return;
            } 
        }
        ~udpClient() {}

    private:
        int _sockfd;
        string _serverip;
        uint16_t _serverport;
    };
} // namespace Client